"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireDefault(require("react"));

var _baseComponent = require("../../extends/baseComponent");

var _index = require("./layouts/index");

var _index2 = require("./adapters/index");

var _isCallable = require("../../utils/is-callable");

var _eventemitter = _interopRequireDefault(require("eventemitter3"));

var _report = _interopRequireDefault(require("../../utils/report"));

var _excluded = ["onConfirm", "onCancel"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

var DialogEmitter = /*#__PURE__*/function (_EventEmitter) {
  _inherits(DialogEmitter, _EventEmitter);

  var _super = _createSuper(DialogEmitter);

  function DialogEmitter() {
    _classCallCheck(this, DialogEmitter);

    return _super.apply(this, arguments);
  }

  return DialogEmitter;
}(_eventemitter.default);

var dialogEmitter = new DialogEmitter();

var Dialog = /*#__PURE__*/function (_baseComponentFactory) {
  _inherits(Dialog, _baseComponentFactory);

  var _super2 = _createSuper(Dialog);

  function Dialog(props) {
    var _this;

    _classCallCheck(this, Dialog);

    _this = _super2.call(this, props);

    _defineProperty(_assertThisInitialized(_this), "onShow", void 0);

    _defineProperty(_assertThisInitialized(_this), "onHide", void 0);

    _defineProperty(_assertThisInitialized(_this), "isControlledComponent", function () {
      return _this.props.visible !== undefined;
    });

    _defineProperty(_assertThisInitialized(_this), "getDefaultState", function (key) {
      return _this.state[key];
    });

    _defineProperty(_assertThisInitialized(_this), "onClose", function () {
      if (!_this.isControlledComponent()) {
        _this.setState({
          visible: false
        });
      }

      if (_this.state.options.onClose && (0, _isCallable.isCallable)(_this.state.options.onClose)) {
        _this.state.options.onClose();
      }
    });

    _defineProperty(_assertThisInitialized(_this), "onCancel", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!(0, _isCallable.isCallable)(_this.state.options.onCancel)) {
                _context.next = 3;
                break;
              }

              _context.next = 3;
              return _this.state.options.onCancel();

            case 3:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    })));

    _defineProperty(_assertThisInitialized(_this), "onConfirm", /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              if (!(0, _isCallable.isCallable)(_this.state.options.onConfirm)) {
                _context2.next = 5;
                break;
              }

              _this.setState({
                confirmDisabled: true
              });

              _context2.next = 4;
              return _this.state.options.onConfirm();

            case 4:
              _this.setState({
                confirmDisabled: false
              });

            case 5:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    })));

    (0, _report.default)({
      componentName: 'dialog'
    });
    _this.state = {
      visible: _this.props.defaultVisible ? _this.props.defaultVisible : false,
      options: _objectSpread({}, _this.props),
      confirmDisabled: _this.props.confirmDisabled
    };

    _this.onShow = function (options) {
      _this.setState({
        visible: true,
        options: _objectSpread(_objectSpread({}, _this.props), options)
      });
    };

    _this.onHide = function () {
      _this.setState({
        visible: false
      });
    };

    if (_this.props.inContext) {
      dialogEmitter.on('show', _this.onShow);
      dialogEmitter.on('hide', _this.onHide);
    }

    return _this;
  }

  _createClass(Dialog, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState, snapshot) {
      var prevVisible = prevProps.visible;
      var currentVisible = this.props.visible;

      if (currentVisible !== prevVisible && !currentVisible) {
        this.onClose();
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      dialogEmitter.off('show', this.onShow);
      dialogEmitter.off('hide', this.onHide);
    }
  }, {
    key: "render",
    value: function render() {
      var RenderComponent = this.RenderComponent;
      return /*#__PURE__*/_react.default.createElement(RenderComponent, _extends({}, this.state.options, {
        confirmDisabled: this.state.confirmDisabled,
        visible: this.isControlledComponent() ? this.props.visible : this.getDefaultState('visible'),
        onClose: this.onClose,
        onCancel: this.onCancel,
        onConfirm: this.onConfirm
      }), this.state.options.content || this.props.children);
    }
  }]);

  return Dialog;
}((0, _baseComponent.baseComponentFactory)({
  viewAdapter: _index.DialogViewAdapter,
  logicalAdapter: _index2.DialogLogicalAdapter
}));

exports.default = Dialog;

_defineProperty(Dialog, "confirm", void 0);

_defineProperty(Dialog, "info", void 0);

_defineProperty(Dialog, "waring", void 0);

_defineProperty(Dialog, "success", void 0);

_defineProperty(Dialog, "error", void 0);

_defineProperty(Dialog, "defaultProps", {
  maskClosable: true,
  mask: true,
  inContext: false,
  width: process.env.DISCUZ_ENV === 'web' ? 400 : 350,
  attach: '',
  title: '',
  type: 'confirm',
  confirmDisabled: false,
  confirmLoading: false,
  cancelBtn: '取消',
  confirmBtn: '确认',
  onCancel: function onCancel() {},
  onConfirm: function onConfirm() {}
});

_defineProperty(Dialog, "show", function () {
  dialogEmitter.emit('show');
});

_defineProperty(Dialog, "hide", function () {
  dialogEmitter.emit('hide');
});

var show = function show(type) {
  if (process.env.DISCUZ_ENV === 'mini') {
    return function (_ref3) {
      var props = _extends({}, _ref3);

      return new Promise(function (resolve) {
        var onConfirm = props.onConfirm,
            onCancel = props.onCancel,
            restProps = _objectWithoutProperties(props, _excluded);

        dialogEmitter.emit('show', _objectSpread(_objectSpread({}, restProps), {}, {
          type: type,
          onConfirm: function () {
            var _onConfirm = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
              return regeneratorRuntime.wrap(function _callee3$(_context3) {
                while (1) {
                  switch (_context3.prev = _context3.next) {
                    case 0:
                      if (!(props.onConfirm && props.onConfirm() instanceof Promise)) {
                        _context3.next = 6;
                        break;
                      }

                      _context3.next = 3;
                      return props.onConfirm();

                    case 3:
                      resolve(true);
                      _context3.next = 7;
                      break;

                    case 6:
                      dialogEmitter.emit('hide');

                    case 7:
                    case "end":
                      return _context3.stop();
                  }
                }
              }, _callee3);
            }));

            function onConfirm() {
              return _onConfirm.apply(this, arguments);
            }

            return onConfirm;
          }(),
          onCancel: function () {
            var _onCancel = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
              return regeneratorRuntime.wrap(function _callee4$(_context4) {
                while (1) {
                  switch (_context4.prev = _context4.next) {
                    case 0:
                      if (!(props.onCancel && props.onCancel() instanceof Promise)) {
                        _context4.next = 6;
                        break;
                      }

                      _context4.next = 3;
                      return props.onCancel();

                    case 3:
                      resolve(false);
                      _context4.next = 7;
                      break;

                    case 6:
                      dialogEmitter.emit('hide');

                    case 7:
                    case "end":
                      return _context4.stop();
                  }
                }
              }, _callee4);
            }));

            function onCancel() {
              return _onCancel.apply(this, arguments);
            }

            return onCancel;
          }()
        }));
      });
    };
  }

  if (process.env.DISCUZ_ENV === 'web') {
    var ReactDOM = require('react-dom');

    return function (_ref4) {
      var props = _extends({}, _ref4);

      return new Promise(function (resolve) {
        var el = document.createElement('div');
        ReactDOM.render( /*#__PURE__*/_react.default.createElement(Dialog, _extends({}, props, {
          type: type,
          inContext: true,
          onClose: function onClose() {
            if (props.onClose && (0, _isCallable.isCallable)(props.onClose)) {
              props.onClose();
            } // TODO: 待增加销毁之后的动画


            ReactDOM.unmountComponentAtNode(el);
          },
          onConfirm: /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() {
            return regeneratorRuntime.wrap(function _callee5$(_context5) {
              while (1) {
                switch (_context5.prev = _context5.next) {
                  case 0:
                    if (!(props.onConfirm && props.onConfirm() instanceof Promise)) {
                      _context5.next = 4;
                      break;
                    }

                    _context5.next = 3;
                    return props.onConfirm();

                  case 3:
                    resolve(true);

                  case 4:
                    ReactDOM.unmountComponentAtNode(el);
                    ;

                  case 6:
                  case "end":
                    return _context5.stop();
                }
              }
            }, _callee5);
          })),
          onCancel: /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6() {
            return regeneratorRuntime.wrap(function _callee6$(_context6) {
              while (1) {
                switch (_context6.prev = _context6.next) {
                  case 0:
                    if (!(props.onCancel && props.onCancel() instanceof Promise)) {
                      _context6.next = 4;
                      break;
                    }

                    _context6.next = 3;
                    return props.onCancel();

                  case 3:
                    resolve(false);

                  case 4:
                    ReactDOM.unmountComponentAtNode(el);

                  case 5:
                  case "end":
                    return _context6.stop();
                }
              }
            }, _callee6);
          }))
        })), el);
        dialogEmitter.emit('show', {});
      });
    };
  }
};

Dialog.confirm = show('confirm');
Dialog.info = show('info');
Dialog.success = show('success');
Dialog.waring = show('warning');
Dialog.error = show('error');

Dialog.hide = function () {
  return dialogEmitter.emit('hide');
};